package com.zrf.testchatgpt.shiro.realm;




import com.zrf.testchatgpt.shiro.token.JwtToken;
import com.zrf.testchatgpt.shiro.util.JwtTokenUtil;
import com.zrf.testchatgpt.util.RedisCacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
//@Component
public class JwtRealm extends AuthorizingRealm {
    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Autowired
    RedisCacheUtil redisCacheUtil;
    @Override
    public String getName() {
        return "JwtRealm";
    }

    /*
     * 多重写一个support
     * 标识这个Realm是专门用来验证JwtToken
     * 不负责验证其他的token（UsernamePasswordToken）
     * */
    @Override
    public boolean supports(AuthenticationToken token) {
        //这个token就是从过滤器中传入的jwtToken
        return token instanceof JwtToken;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//        log.info("jwt的授权方法");
//        if(principals == null){
//            throw new AuthorizationException("principals should not be null");
//        }
//        Users userInfo= (Users) SecurityUtils.getSubject().getPrincipal();
//        Session session = SecurityUtils.getSubject().getSession(true);
//        session.setAttribute("uid",userInfo.getUserOpenid());
//        System.out.println("用户-->"+userInfo.getWxName()+"获取权限中");

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
//            simpleAuthorizationInfo.addRole("admin");//添加角色名字
//            simpleAuthorizationInfo.addStringPermission("admin_save");
//        System.out.println("角色为-> " + simpleAuthorizationInfo.getRoles());
//        System.out.println("权限为-> " + simpleAuthorizationInfo.getStringPermissions());
        return simpleAuthorizationInfo;
    }

    //认证
    //这个token就是从过滤器中传入的jwtToken
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//        UsernamePasswordToken passwordToken = (UsernamePasswordToken) token;
        //获取用户输入的用户名密码
        String username= (String) token.getPrincipal();
        String password=new String((char[])token.getCredentials());
        System.out.println("用户输入--->username:"+username+"-->password:"+password);
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                username, // 用户名
                password, // 密码
                getName() // realm name
        );

        return authenticationInfo;
    }

}
